import personInfo from '@/views/client-manage/components/person-info.vue'
import providerPersonInfo from '@/views/client-manage/components/provider-person-info.vue'
import uploadMedia from '@/components/upload-media.vue'
import {getDivision,getObjByCode} from '@/admin/api/division'
import {getObj, addObj, putObj, cardCheck} from '@/views/client-manage/api/clientprovider'
import {mapState} from "vuex";
import {getDictAndPlease} from "~/utils"
import {validatePhone, validateEmail,validateTelephone, validateIdNo,validateTel} from '~/utils/validate'

export default {
    components: {
        personInfo,
        uploadMedia,
        providerPersonInfo
    },
    computed: {
        selectProvice: function () {
            return this.provinces.find(p => p.value == this.propForm.provinceCode)
        },
        selectCity: function () {
            return this.citys.find(p => p.value == this.propForm.cityCode)
        },
        selectCounty: function () {
            return this.countys.find(p => p.value == this.propForm.countyCode)
        },
        chArea: function () {
            let p = this.selectProvice ? this.selectProvice.label : ''
            let c = this.selectCity ? this.selectCity.label : ''
            let y = this.selectCounty ? this.selectCounty.label : ''
            return p + c + y
        }
    },
    props: {},
    data() {
        //社会信用码验证
        var validCertificateNum = (rule, value, callback) => {
            if (this.propForm.certificateType == 2) {
                let Ancode;//统一社会信用代码的每一个值
                let Ancodevalue;//统一社会信用代码每一个值的权重
                let total = 0;
                let weightedfactors = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];//加权因子
                //不用I、O、S、V、Z
                let str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
                for (let i = 0; i < value.length - 1; i++) {
                    Ancode = value.substring(i, i + 1);
                    Ancodevalue = str.indexOf(Ancode);
                    total = total + Ancodevalue * weightedfactors[i];
                    //权重与加权因子相乘之和
                }
                let logiccheckcode = 31 - total % 31;
                if (logiccheckcode == 31) {
                    logiccheckcode = 0;
                }
                let Str = "0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F,G,H,J,K,L,M,N,P,Q,R,T,U,W,X,Y";
                let Array_Str = Str.split(',');
                logiccheckcode = Array_Str[logiccheckcode];
                let checkcode = value.substring(17, 18);
                if (logiccheckcode != checkcode) {
                    callback(new Error('校验失败，请输入正确的统一社会信用代码！'));
                }
            }
            if (this.propForm.certificateType == 1) {
                if (value === "") {
                    callback(new Error("请输入组织机构代码"));
                } else if (value.length != 9) {
                    callback(new Error("组织机构代码位数不正确"));
                } else {
                    // var patrn = /^[0-9A-Z]+$/;
                    var reg = /^[0-9A-Z]+$/;
                    if (reg.test(value) == false) {
                        callback(new Error("组织机构代码只可为数字或大写拉丁字母"));
                    } else {
                        var regLast = /^[0-9X]+$/;

                        var lastnum = value.substring(8, 9);

                        if (regLast.test(lastnum) == false) {
                            callback(
                                new Error("组织机构代码最后一位只可为数字或大写拉丁字母 X")
                            );
                        } else {
                            var ancode;
                            var ancodeWeightValue;
                            var sum = 0;
                            var weightedArray = [3, 7, 9, 10, 5, 8, 4, 2]; //加权因子
                            var str = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
                            for (var i = 0; i < value.length - 1; i++) {
                                ancode = value.substring(i, i + 1);
                                ancodeWeightValue = str.indexOf(ancode);
                                sum = sum + ancodeWeightValue * weightedArray[i];
                            }
                            var rightLastnum = 11 - (sum % 11);
                            if (rightLastnum == 10) rightLastnum = "X";
                            if (rightLastnum == 11) rightLastnum = "0";
                            if (lastnum != rightLastnum) {
                                callback(new Error("组织机构代码结构错误！"));
                            }
                        }
                    }
                }
            }
            if (this.propForm.certificateType == 0) {
                var msg = this.checkCode(value)
                if (msg.length > 0) {
                    callback(new Error(msg));
                }
            }
            if (this.propForm.certificateType == 3) {
                var flag = this.isTaxAdministration(value);
                if (flag == false) {
                    callback(new Error('税务登记号有误 ！'));
                }
            }
            let certificateType = this.propForm.certificateType;
            let clientLesseeType = this.propForm.clientLesseeType

            if(!this.originalCertificateNum===this.propForm.certificateNum){
                cardCheck({"clientLesseeType":clientLesseeType,"certificateType":certificateType,"certificateNum":value}).then(respdata => {
                    var item=respdata.data.data
                    if (item.length> 0) {
                        callback(new Error('校验失败，该证件号码已经存在 ！'));
                    } else {
                        callback()
                    }
                })
            }else {
                callback()
            }

        }

        return {
            propForm: {
                clientProviderId: '',
                clientProviderName: '',
                clientProviderType: '',
                certificateType: '',
                certificateNum: '',
                providerPrincipal: '',
                phoneNum: '',
                email: '',
                telephone: '',
                scopeBusiness: '',
                areaCode:'',
                address:'',
                introduceUnit: '',
                shxyNum: '',
                zzjgNum: '',
            },
            originalCertificateNum: '',
            optionVal: '',
            uploadFileList: [],
            modelType: 'supplierManage',
            rules: {
                clientProviderName: [{required: true, message: '供应商名称不能为空', trigger: 'blur'},
                    {min: 0, max: 24, message: "长度在0-24个字符串", trigger: "blur"},],
                remarks: [
                ],
                clientProviderType: [{required: true, message: '供应商类型不能为空', trigger: 'blur'}
                ],
                certificateType: [{required: true, message: '证件类型不能为空', trigger: 'blur'}
                ],
                providerPrincipal: [
                ],
                phoneNum: [{required: true, message: '联系电话不能为空', trigger: 'blur'},
                    {validator:validatePhone,trigger: "blur"},
                ],
                email: [{required: true, message: '电子邮箱不能为空', trigger: 'blur'},
                    {validator: validateEmail, trigger: "change"},
                ],
                telephone: [{required: true, message: '固定电话不能为空', trigger: 'blur'},
                   {validator: validateTel, trigger: "change"},
                ],
                scopeBusiness: [
                ],
                addressInfo: [
                ],
                address: [
                ],
                introduceUnit: [],
                certificateNum: [
                    {validator: validCertificateNum, trigger: 'change'},
                    //{validator: validCertificateNum, trigger: 'blur'},
                ],

            },
            editPersons: [],
            delPersons: [],

            provinces: [],
            citys: [],
            countys: [],
            isAdd: true,
            busId: '',

            url: '/admin/sys-file/upLodeFileAdd',
            fileSize: 50,
            isEdit: false,
            //供应商类型字典值
            providerOptions: [],
            providerOptionsCopy: [],
            certificateOptions: [],
            certificateOptionsCopy: [],
            //这个属性用于判断联系人的类型是供应商还是承租商，根据不同的类型，person-info查询不同的数据
            clientType: 'provider',

        }
    },
    created() {
        if (this.isAdd) {
            this.initClientProviderType()
        }
        if (!this.$route.query.id){
            this.$route.meta.title = '新增'
        }else {
            this.$route.meta.title = '编辑'
        }
        //获取传递过来的url参数
        this.propForm.clientProviderId = this.$route.query.id
        if (this.propForm.clientProviderId) {
            this.isEdit = true;
            this.initCitySelector()
        } else {

        }
    },
    mounted() {

    },
    methods: {
        queryItem() {
            getObj(this.propForm.clientProviderId).then(respdata => {
                this.propForm = respdata.data.data;
                //将客户类型转化为字符串，结合下拉列表
                this.propForm.clientProviderType += ''
                this.propForm.certificateType += ''

                this.optionVal = this.propForm.clientProviderType
            })
        },
        //监听省市区下拉




        initClientProviderType() {
            this.providerOptions = getDictAndPlease('provider_type')
            this.providerOptionsCopy = this.providerOptions;
        },
        queryCertificateType() {
            this.certificateOptions = getDictAndPlease('commercial_certificate_type')
            this.certificateOptionsCopy = this.certificateOptions
        },

        async initCitySelector() {
            this.busId = this.propForm.clientProviderId

            await getObj(this.propForm.clientProviderId).then((rep) => {
                this.isAdd = false;
                this.propForm = rep.data.data;
                //将客户类型转化为字符串，结合下拉列表
                this.propForm.clientProviderType += ''
                this.propForm.certificateType += ''
                this.optionVal = this.propForm.clientLesseeType
                this.originalCertificateNum = this.propForm.certificateNum
                //获取省市县区下拉数据
                //如果是编辑状态，生成addressInfo详细地址
/*
                var index1=this.propForm.address.lastIndexOf("市")
                var index2=this.propForm.address.lastIndexOf("区")
                var index3=this.propForm.address.lastIndexOf("县")
                var max = index1>index2 ? index1 : index2
                max= max>index3 ? max : index3
                this.propForm.addressInfo=this.propForm.address.substring(max+1)*/

                //qh+:编辑状态初始化时查询证件类型，客户类型
                this.initClientProviderType();
                if (this.propForm.clientProviderType) {
                    this.queryCertificateType()
                }
            })
            this.$refs.ProviderFiles.getFiles(this.busId)
        },
        submit() {
            this.$refs.privoderPersonInfo.check()
        },
        submitForm(val) {

            this.propForm.areaCode=this.propForm.provinceCode+this.propForm.cityCode+this.countryCode;
            /*if( this.propForm.addressInfo){
                this.propForm.address = this.chArea + this.propForm.addressInfo
            }else {
                this.propForm.address = this.chArea
            }*/
            for (var i = 0; i < this.editPersons.length; i++) {
                this.editPersons[i].clientProviderId = val
            }

            this.$refs.propForm.validate(valid => {
                if (valid) {

                    if (this.propForm.supplierId) {
                        for (let i = 0; i < this.editPersons.length; i++) {
                            this.editPersons[i].supplierId = this.propForm.supplierId
                        }
                        putObj(Object.assign({}, this.propForm, {clientProviderLinkinfos: this.editPersons}, {delClientProviderLinkinfos: this.delPersons})).then(rep => {
                            if (rep.data.code === 0) {
                                this.$store.commit("delHistoryRoute", this.$route.fullPath);
                                this.$router.push("/client-manage/provider-manage")
                            } else {
                                this.$message.error("add-error");
                            }
                        })
                    } else {
                        this.propForm.supplierId = val
                        addObj(Object.assign({}, this.propForm, {clientProviderLinkinfos: this.editPersons})).then(rep => {

                            if (rep.data.data) {
                                this.$store.commit("delHistoryRoute", this.$route.fullPath);
                                this.$router.push("/client-manage/provider-manage")
                            } else {
                                this.$message.error("add-error");
                            }
                        })
                    }
                }
            })
        },

        commit() {
            // this.$refs.editForm.validate(valid => {
            //     if (valid) {
            if (this.uploadFileList.length > 0) {
                this.$refs.ProviderFiles.submit(this.modelType,this.propForm.clientProviderId);
            } else {
                this.submitForm()
            }
        },
        changeclientProviderType(val) {
            this.optionVal = this.propForm.clientProviderType
        },

        beforeUpload() {
            // this.loadAction('请稍等...')
        },
        onSuccess(response, file, fileList) {

            this.fileList = []
            this.submitForm(response.data)

        },
        onError(err, file, fileList) {
            this.err('提交失败')
        },
        dataFilter(val) {
            this.formData.clientProviderType = val;
            if (val) { //val存在
                this.providerOptions = this.providerOptionsCopy.filter((item) => {
                    if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
                        return true
                    }
                })
            } else { //val为空时，还原数组
                this.providerOptions = this.providerOptionsCopy;
            }
        },
        certificateDataFilter(val) {
            this.formData.certificateType = val;
            if (val) { //val存在
                this.certificateOptions = this.certificateOptionsCopy.filter((item) => {
                    if (!!~item.label.indexOf(val) || !!~item.label.toUpperCase().indexOf(val.toUpperCase())) {
                        return true
                    }
                })
            } else { //val为空时，还原数组
                this.certificateOptions = this.certificateOptionsCopy;
            }
        },
        //qh+:营业执照验证
        checkCode(value) {
            if (value.length != 18) {
                return "营业执照长度错误！";
            }
            var reg = /^([0-9ABCDEFGHJKLMNPQRTUWXY]{2})([0-9]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-9Y])$/;
            if (!reg.test(value)) {
                return "营业执照校验错误！";
            }
            var str = '0123456789ABCDEFGHJKLMNPQRTUWXY';
            var ws = [1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28];
            var values = new Array();
            values[0] = value.substr(0, value.length - 1);
            values[1] = value.substr(value.length - 1, value.length);
            var sum = 0;
            for (var i = 0; i < 17; i++) {
                sum += str.indexOf(values[0].charAt(i)) * ws[i];
            }
            var c18 = 31 - (sum % 31);
            if (c18 == 31) {
                c18 = 'Y';
            } else if (c18 == 30) {
                c18 = '0';
            }
            if (c18 != values[1]) {
                return "营业执照代码有误！" + c18;
            }
        },
        //qh+：税务登记号验证
        isTaxAdministration(card) {
            let reg = /^([A-Z0-9]{15}|[A-Z0-9]{17}|[A-Z0-9]{20})$/;
            return reg.test(card)
        },
        getMax(num1,num2,num3){
            alert(num1)
            max = num1>num2 ? num1 : num2;
            return max>num3 ? max : num3;
        }
    }
};
